from flask import (Blueprint,Flask,request,session,Response, jsonify,make_response)
import json
from jwt import JWT as jwt
from jwt import jwk
bp = Blueprint("login", __name__)
 
from src.database.getdb import database 
db=database().create_db()
from src.database.redis import Db_Redis
from const import respond_header,secret_key

import hashlib

#在app.py引入蓝图，在这不生效
# app = Flask(__name__)


from functools import wraps

# 装饰器装饰多个视图函数
def checklogin(func):
    # 保存原来函数的所有属性,包括文件名
    @wraps(func)
    def inner(*args,**kwrags):
        # 校验session
        if session.get("user",""):
            # func = home
            print(session.get("user",""))
            ret=func(*args,**kwrags)
            return ret
        return {}
    return inner




@bp.route('/login')
def entrance():
    data={'code':1}
    if request.method == "GET":
        username = request.args.get("username").strip()
        password = request.args.get("password").strip()
        data = Login().entrance(username,password)

    return json.dumps(data)

@bp.route('/login/outlogin')
def outlogin():
    session["user"] =''
    return respond_header

class Login(Db_Redis):
    def entrance(self,username,password):
        data=respond_header  

        sql ="select password from dzpk_user where username='%s'"%(username,)
        with  db.cursor() as cursor:
            # try:
                cursor.execute(sql)
                mess = cursor.fetchall()
                if len(mess) >0:
                    for e in mess:
                        e=list(e)
                        if e[0] == password:
                            session["user"]=username
                            # cookies = request.cookies.get('user')
                            cookies = hashlib.md5(username.encode(encoding='UTF-8')).hexdigest()
                                            
                            data['code'] =1
                            data['mess'] ='登陆成功'
                            data['Set-Cookie'] =cookies
                            data['SameSite'] =None
                            token = generate_token(username,password)
                            data['token'] = token

                            print(token)
                        else:
                            data['code'] =0
                            data['mess'] ='密码错误'
                else:
                    data['code'] =0
                    data['mess'] ='帐号错误'

                cursor.close()
                
            # except :
            #     data['code'] =0
                #   data['mess'] ='帐号错误'
                

        return data


 
    def make_token(self):
        
        token = generate_token()  # 生成Token函数
        resp = make_response('Login successful!', 200)
        resp.set_cookie('token', token)  # 设置Cookie
        return resp

def generate_token(user,passw):
    data={
        'user':user,
        'passw':passw
    }
    token = jwt().encode(data,jwk.OctetJWK(secret_key.encode()), alg='HS256')
    return token



